package lt.ntec.danblog.server.core.model.gae;

import java.util.HashSet;
import java.util.Set;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import lt.ntec.danblog.server.core.model.Tag;
import lt.ntec.danblog.server.core.model.Taggable;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@PersistenceCapable
class JDOTag implements Tag, Comparable<Tag> {

    @Persistent
    private HashSet<JDORelationMap> parents = new HashSet<JDORelationMap>();
    @Persistent
    private HashSet<Key> parentKeys = new HashSet<Key>();
    @NotPersistent
    private HashSet<Taggable> parentsObj = new HashSet<Taggable>();
    @Persistent
    private String value;
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    JDOTag(String value, Taggable parent) {
        Key k = KeyFactory.createKey(parent.getClass().getSimpleName(),
                parent.getId());
        this.value = value;
        this.parents.add(new JDORelationMap(parent.getClass().getName(), k));
        this.parentKeys.add(k);
        this.parentsObj.add(parent);
    }

    @Override
    public String getValue() {
        return value;
    }

    public boolean equals(Object obj) {
        return (this.getValue().toLowerCase().equals(((JDOTag) obj).getValue().toLowerCase()));
    }

    @Override
    public Long getId() {
        return key.getId();
    }

    @Override
    public int compareTo(Tag o) {
        return o.getValue().compareTo(this.getValue()) * (-1);
    }

    @Override
    public Set<? extends Taggable> getEntryList() {
        if (parentsObj == null) {
            parentsObj = new HashSet<Taggable>();
        }
        return parentsObj;
    }

    @Override
    public void addParent(Taggable entity) {
        Key k = KeyFactory.createKey(entity.getClass().getSimpleName(),
                entity.getId());
        parentsObj.add(entity);
        parents.add(new JDORelationMap(entity.getClass().getName(), k));
        parentKeys.add(k);
    }

    @Override
    public void removeParent(Taggable entity) {

        Key k = KeyFactory.createKey(entity.getClass().getSimpleName(),
                entity.getId());
        parents.remove(new JDORelationMap(entity.getClass().getName(), k));
        parentKeys.remove(k);
        parentsObj.remove(entity);
    }

    public HashSet<Key> getParentKeys() {
        return parentKeys;
    }

    public HashSet<JDORelationMap> getParentMap() {
        return parents;
    }

    public void setParents(HashSet<Taggable> parentsObj) {
        this.parentsObj = parentsObj;
    }
}
